#!/usr/bin/perl -w
# Create a Javascript record set of MCAS test item responses per student
# from a tab-delimited input file with 21 fields, including a header row
# at the top of the file:
#
#    (0) Student Code    (10) Standard            (20) Reporting District
#    (1) Subject ID      (11) Question Type
#    (2) Subject         (12) Item Text
#    (3) Grade           (13) Correct Response
#    (4) Year            (14) Student Response
#    (5) Month           (15) Correct MC
#    (6) Item            (16) Possible MC
#    (7) Strand ID       (17) Student Points
#    (8) Strand          (18) Possible Points
#    (9) Standard ID     (19) School
#
# Input records are sorted by student, subject ID, grade, year, and item number.
#   
# Output records
#    Student Code
#    Subject
#    Grade
#    Year
#    Item Response String, e.g., AC3E++-+.

print "var studentResponses = [\n";
my $headers = <>; chomp $headers;
my ($rec_student, $rec_subject, $rec_grade, $rec_year, @rec_responses)
  = (0, 'none', 0, 0, ());
while (<>) {
    chomp;
    my ($student, $subject_ID, $subject, $grade, $year, $month, $item, $strand_ID,
        $strand, $standard_ID, $standard, $question_type, $item_text,
        $correct_response, $student_response, $correct_MC, $possible_MC,
        $student_points, $possible_points,
        $school, $reporting_district) = split /\t/;

    if ($student ne $rec_student
    || $subject ne $rec_subject
    || $grade ne $rec_grade
    || $year ne $rec_year) {
        if ($rec_student) {
            print_record($rec_student, $rec_subject, $rec_grade, $rec_year, @rec_responses);
        }
        ($rec_student, $rec_subject, $rec_grade, $rec_year) 
         = ($student, $subject, $grade, $year);
    }
    $rec_responses[$item] = $student_response;
}
print_record($rec_student, $rec_subject, $rec_grade, $rec_year, @rec_responses);
print "];\n";

sub print_record {
    my ($student, $subject, $grade, $year, @responses) = @_;
    for (my $pos = 1; $pos < @responses; $pos++) {
        if (length($responses[$pos]) != 1) {  # missing response?
                $responses[$pos] = ' ';  # use blank character
            }
    }
    my $response_string = join('', @responses[1..$#responses]);
    $, = ',';
    print '[' . $rec_student, 
        "'" . $rec_subject . "'", 
        $rec_grade,
        $rec_year,
        "'" . $response_string . "'],\n";
    $, = undef;
}
